<?php

/**
 * 部门模型
 */

namespace app\api\model;

use think\Db;
use app\api\model\Common;
use think\Validate;

class Department extends Common
{
    /**
     *  主键查数据
     *  参数
     *  id 主键id
     */
    public function getDataId($id)
    {
        $data = $this->get($id);
        if (!$data) {
            $this->error = '暂无此数据';
            return false;
        }
        return $data;
    }

    /**
     *  插入数据，并且更新num编号
     *  参数
     *  $param 插入数据
     *  $pnum 父部门 编号
     */
    public function addDate($param, $pnum)
    {
        // 验证
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        //事务处理
        Db::startTrans();
        try {
            //获取主键
            $id = $this->allowField(true)->insertGetId($param);
            $num = $pnum . ',' . $id . ',';
            $this->save(['num' => $num], [$this->getPk() => $id]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            //回滚
            Db::rollback();
            $this->error = '添加失败';
            return false;
        }
    }

    /**
     * 查询数据列表
     * 参数
     * param 符合数据库属性的数组，默认为空
     * $param 符合数据库属性的键值数组 
     * $limit 每页数量 
     * $page  页数  
     */
    public function getDate($param, $limit, $page, $time, $match)
    {
        try {
            $result = $this->where($param)->where('update_time', 'between', $time)->where('title', 'like', '%' . $match . '%')->limit($limit)->page($page)->select();
            if ($result === false) {
                return false;
            }
            return $result;
        } catch (\Exception $e) {
            //throw new \Exception("查找失败");
            return false;
        }
    }


    /**
     * 更新数据
     * 参数
     * $param  符合数据库属性的键值数组 
     * $rules  自定义的更新验证规则
     * $id     主键id
     */
    public function updateDate($param, $rules, $id)
    {
        // 验证
        if (isset($rules) && is_array($rules)) {
            $validate = new Validate($rules);
            if (!$validate->check($param)) {
                $this->error = $validate->getError();
                return false;
            }
        }
        try {
            //按id更新status
            $result = $this->allowField(true)->save($param, [$this->getPk() => $id]);
            if ($result) {
                return true;
            }
        } catch (\Exception $e) {
            $this->error = '更新失败';
            return false;
        }
        return false;
    }

    /**
     * 创建群组，关联用户
     */
    public function createDate($param, $uids = array())
    {
        try {
            // 验证
            $validate = validate($this->name);
            if (!$validate->check($param)) {
                $this->error = $validate->getError();
                return false;
            }
            Db::startTrans();
            $did = $this->allowField(true)->insertGetId($param);
            $gu_model = Model('GroupUser');
            foreach ($uids as &$param) {
                $param = [
                    'uid' => $param,
                    'did' => $did
                ];
            }
            $gu_model->createData($uids);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            //$this->error = $e->getMessage();
            $this->error = '更新失败';
            return false;
        }
    }

    /**
     * 群组列表
     */
    public function getList($condition, $keyword, $page, $limit)
    {
        if ($condition) {
            $map[$condition] = ['like', '%' . trim($keyword) . '%'];
        }
        $total =  $this->where($map)->count();
        $result = $this->where($map)->limit($limit ? $limit : $total)->page($page ? $page : 1)->field('dptid as id,title')->order('dptid asc')->select();
        $data = [
            'list' => $result,
            'total' => $total,
            'totalPage' => $limit ? $limit : 1
        ];

        return $data;
    }

    /**
     * 更新群组操作
     */
    public function updateDataById($id, $param)
    {
        if(!$id){
            $this->error = 'id不能为空';
            return false;
        }
        $checkData = $this->get($id);
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }

        // 验证
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }

        try {
            Db::startTrans();
            $this->allowField(true)->save($param, [$this->getPk() => $id]);
            if (!empty($param['ids'])) {
                $uids = explode(',', $param['ids']);
                foreach ($uids as &$uid) {
                    $uid = [
                        'uid' => $uid,
                        'did' => $id
                    ];
                }
                $gu_model = Model('GroupUser');
                $gu_model->destroy(['did' => $id]);
                $gu_model->createData($uids);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            //echo $e->getMessage();
            $this->error = '编辑失败';
            return false;
        }
    }

    /**
     * 获取详情
     */
    public function getDataDetail($id){
        $_data = $this->get($id);
        if(!$_data){
            $this->error = '暂无此数据';
            return false;
        }
        $_data_detail = Model('GroupUser')->getUnionList($id);
        $result['list'] = array();
        //格式处理 改成 id/username 格式
        while(NULL !== ($_val = array_pop($_data_detail))){
            $result['list'][] = $_val['user']['id'] . '/' . $_val['user']['username'];
        }   
        $result['title'] =  $_data->title;
        $result['dptid'] =  $_data->dptid;
        return $result;
    }
}
